package start;
// This file contains material supporting section 3.7 of the textbook:
// "Object Oriented Software Engineering" and is issued under the open-source
// license found at www.lloseng.com 

import java.io.*;
import java.sql.ResultSet;
import java.util.StringTokenizer;


import client.*;

import database.*;
import ocsf.server.*;

/**
 * This class overrides some of the methods in the abstract 
 * superclass in order to give more functionality to the server.
 *
 * @author Dr Timothy C. Lethbridge
 * @author Dr Robert Lagani&egrave;re
 * @author Fran&ccedil;ois B&eacute;langer
 * @author Paul Holden
 * @version July 2000
 */
public class EchoServer extends AbstractServer 
{
  //Class variables *************************************************
  
  /**
   * The default port to listen on.
   */

  final public static int DEFAULT_PORT = 5555;

	public ServerMsgLogIn sermsg;
	public Student stu;
	public Teacher teach;
	public SecretaryANDPrincipal SEC_and_PRIN;
	public Parents parent;
	public Course course;
  //Constructors ****************************************************
  
  /**
   * Constructs an instance of the echo server.
   *
   * @param port The port number to connect on.
   */
  public EchoServer(int port) 
  {
    super(port);
  }

  
  //Instance methods ************************************************
  
  /**
   * This method handles any messages received from the client.
   *
   * @param msg The message received from the client.
   * @param client The connection from which the message originated.
   */
  public void handleMessageFromClient
    (Object msg, ConnectionToClient client)
  	{
	  int flag_of_window=-1;				//number of window that not exist 
	  String str,quary;
	  str=msg.toString();
	  StringTokenizer st = new StringTokenizer (str, ";", false);	//Separate the msg that we sent with the number of window , quary and more 
	  flag_of_window=Integer.parseInt(st.nextToken());	//this is the number of window/idea that we want to know
	  quary=st.nextToken();//this is the query
	  switch(flag_of_window)						//when you enter in the first time we check in the data base on user if the user exist in the table of users and sent the data to the main window log in 
	  {
	  	
	  		case 1:				//enter window for all user 
	  				try //try 1
	  				{
	  					
	  					sermsg = new ServerMsgLogIn();
	  					DataBaseConection a = new DataBaseConection();
	  					ResultSet Rs=a.st.executeQuery(quary);
	  					
	  						if(Rs.first()==false)
	  						{
	  							
	  							sermsg.UserName="";
	  							sermsg.Password="";
	  							sermsg.BlockIndex="";
	  							sermsg.User_Type="";
	  						}
			
	  							else
	  							{
	  								sermsg.UserName=Rs.getString(1);
	  								sermsg.Password=Rs.getString(2);
	  								sermsg.User_Type=Rs.getString(3);
	  								sermsg.BlockIndex=Rs.getString(4);
	  								
	  							}
			Rs.close();
			client.sendToClient(sermsg);
			
			break;
			
	  				}//try 1 end
		
			
		catch (Exception e) //catch to try 1
				{
				System.out.print("the mesasss"+e.getMessage());
				}
	  				
	  		case 2:									//main window get detail on this student that he is user also 
		
	  				try {//try2
	  					
	  					DataBaseConection a = new DataBaseConection();
	  					System.out.println(quary);
	  					ResultSet Rs=a.st.executeQuery(quary);
	  					Rs.first();
	  					stu=new Student(Rs.getString(1), Rs.getString(2),Rs.getString(3),Rs.getString(4), Rs.getString(5));
		  				Rs.close();
		  				client.sendToClient(stu);
		  				
	  					} //try 2 end

	  				
	  		catch (Exception e)
	  		{
			// TODO Auto-generated catch block
			e.printStackTrace();
	  		}
					
	  			break;	//break 2
	  			
	  			
	  		case 3:									//main window get detail on this teacher that he is user also 
	  			
  				try {//try3
  					
  					DataBaseConection a = new DataBaseConection();
  					ResultSet Rs=a.st.executeQuery(quary);
  					Rs.first();
  					teach=new Teacher(Rs.getString(1), Rs.getString(2),Rs.getString(3),Rs.getString(4), Rs.getString(5));
	  				Rs.close();
	  				client.sendToClient(teach);
	  				
  					} //try 3 end

  				
  		catch (Exception e)
  		{
		// TODO Auto-generated catch block
		e.printStackTrace();
  		}
				
  			break;	//break 3	
	  			
	  		case 4:									//main window get detail on this parents that he is user also 
	  			
  				try {//try4
  					
  					DataBaseConection a = new DataBaseConection();
  					ResultSet Rs=a.st.executeQuery(quary);
  					Rs.first();
  					
  					int sign_sec_or_princ=Integer.parseInt(st.nextToken());//check if what is send is teacher or principal
  					
  						if(sign_sec_or_princ==0)//secretary
  							 SEC_and_PRIN =new SecretaryANDPrincipal(0,Rs.getString(1), Rs.getString(2),Rs.getString(3));//all the different is the 1 or 0
  						else
  							 SEC_and_PRIN =new SecretaryANDPrincipal(0,Rs.getString(1), Rs.getString(2),Rs.getString(3));
  						
	  				Rs.close();
	  				client.sendToClient(SEC_and_PRIN);
	  				
  					} //try 4 end

  				
  				catch (Exception e)
  				{
  					// TODO Auto-generated catch block
  					e.printStackTrace();
  				}
				
  			break;	//break 4	
  			
  			
  			
	  		case 5:									//main window get detail on this teacher that he is user also 
	  			
  				try {//try5
  					
  					DataBaseConection a = new DataBaseConection();
  					ResultSet Rs=a.st.executeQuery(quary);
  					Rs.first();
  					parent=new Parents(Rs.getString(1), Rs.getString(2),Rs.getString(3));
  					
	  				Rs.close();
	  				client.sendToClient(parent);
	  				
  					} //try 5 end

  				
  		catch (Exception e)
  		{
		// TODO Auto-generated catch block
		e.printStackTrace();
  		}
				
  			break;	//break 5	
	  			
	  		case 6:									//delete course from database by course id  
	  			
  				try {//try6
  					DataBaseConection a = new DataBaseConection(1);
  					ResultSet Rs=a.st.executeQuery(quary);
  					if(Rs.first())
  					{
  					Rs.deleteRow();
  					client.sendToClient("1;The course was deleted successfully");//THE NUMBER 1 ITS TELL AS IN THE FUNCTION THAT WE KNOW THE DELETE successfully
  					}
  					else
  					client.sendToClient("2;The course is not found please enter again");//THE NUMBER 2 ITS TELL AS IN THE FUNCTION THAT WE KNOW THE DELETE NOT successfully BECAUSE THERE IS NOT COURSE ID LIKE THIS
  					  					
	  			    Rs.close();		 

  					} //try 6 end
  				

  				
  		catch (Exception e)
  		{
		// TODO Auto-generated catch block
		e.getMessage();
  		}
				
  			break;	//break 6	
  			
	  		case 7:									//update course from database by course id  
	  			
  				try {//try7
  					DataBaseConection a = new DataBaseConection();
  					ResultSet Rs=a.st.executeQuery(quary);
  					if(Rs.first())
  					{	
  					course=new Course(Rs.getString(1), Rs.getString(2), Rs.getString(3),Rs.getString(4), Rs.getString(5));
  					course.course_available=1;//that tell us there is course like this 	
  					client.sendToClient(course);//send the istance of course 
  					}
  					else
  					client.sendToClient("The course is not found please enter again");//error message and tell us the diffrent between failer and successfully
  					  					
	  			    Rs.close();		 

  					} //try 7 end
  				

  				
  		catch (Exception e)
  		{
		// TODO Auto-generated catch block
		e.getMessage();
  		}
				
  			break;	//break 7		
  			
  			
	  		case 8:									//update course from database by course id  
	  			
  				try {//try8		

  					DataBaseConection a = new DataBaseConection(1);	
  					ResultSet Rs=a.st.executeQuery(quary);
  					if(Rs.first())
  					{	

  						Rs.updateString(2,st.nextToken());
  						Rs.updateString(3,st.nextToken());
  						Rs.updateString(4,st.nextToken());
  						Rs.updateString(5,st.nextToken());
  						Rs.updateRow();
  					client.sendToClient("1;The updated completed");//send ok message and 1 tell us this 
  					}
  					else
  					client.sendToClient("2;The updated failed");//error message and tell us the diffrent between failer and successfully
  					  					
	  			    Rs.close();		 

  					} //try 8 end
  				

  				
  		catch (Exception e)
  		{
		// TODO Auto-generated catch block
		e.getMessage();
  		}
				
  			break;	//break 8	
  			
  			
  			
	  		case 9:									//update course from database by course id  
	  			
  				try {//try9		
  					
  					String massge_check_course=st.nextToken();//anoter qurey that check course id if exsist already 
  					DataBaseConection b = new DataBaseConection();//conection for regular qurey
  					ResultSet Rs=b.st.executeQuery(massge_check_course);
  					if(Rs.first())
  						client.sendToClient("2;The course id already exsist");//error message and tell us the course is alredy exsist 	
  					Rs.close();
  					
  					DataBaseConection a = new DataBaseConection(1);	
  					ResultSet Rs1=a.st.executeQuery(quary);
  					Rs1.moveToInsertRow();
  					
  						Rs1.updateString(1,st.nextToken());
  						Rs1.updateString(2,st.nextToken());
  						Rs1.updateString(3,st.nextToken());
  						Rs1.updateString(4,st.nextToken());
  						Rs1.updateString(5,st.nextToken());
  						Rs1.insertRow();
  					
  					client.sendToClient("1;The created completed");//send ok message and 1 tell us this 
  						  					
	  			    Rs1.close();		 

  					} //try 9 end
  				

  				
  		catch (Exception e)
  		{
		// TODO Auto-generated catch block
		e.getMessage();
  		}
				
  			break;	//break 9
  			
  			
	  		case 10:									//check if the id of something(sometable) is exsist return the right message  
	  			
  				try {//try10		
  					
  				 
  					DataBaseConection a = new DataBaseConection();//conection for regular qurey
  					ResultSet Rs=a.st.executeQuery(quary);
  					if(Rs.first())
  						client.sendToClient("1;The id is exsist in the table");//send the number 1 and tell us the id is exsist in the table we ask 
  					else
  						client.sendToClient("2;The id is not exsist in the table");//send the number 2 and tell us the id is not exsist in the table we ask 
  					Rs.close();
  					} //try 10 end
  				

  				
  		catch (Exception e)
  		{
		// TODO Auto-generated catch block
		e.getMessage();
  		}
				
  			break;	//break 10	
  			
  			
	  		case 11:									//remove row something(sometable) is exsist return the right message  
	  			
  				try {//try11		
  					
  				 
  					DataBaseConection a = new DataBaseConection(1);
  					ResultSet Rs=a.st.executeQuery(quary);
  					if(Rs.first())
  					{
  					Rs.deleteRow();
  					client.sendToClient("1;The row in Table (((need to change))) was deleted successfully");//THE NUMBER 1 ITS TELL AS IN THE FUNCTION THAT WE KNOW THE DELETE successfully
  					}
  					else
  					client.sendToClient("2;The course is not found please enter again");//THE NUMBER 2 ITS TELL AS IN THE FUNCTION THAT WE KNOW THE DELETE NOT successfully BECAUSE THERE IS NOT COURSE ID LIKE THIS
  					  					
	  			    Rs.close();		
  					} //try 11 end
  				

  				
  		catch (Exception e)
  		{
		// TODO Auto-generated catch block
		e.getMessage();
  		}
				
  			break;	//break 11	
  			
  			
  			
	  }//switch

	}//end func handleMessageFromClient

    
  /**
   * This method overrides the one in the superclass.  Called
   * when the server starts listening for connections.
   */
  protected void serverStarted()
  {
    System.out.println
      ("Server listening for connections on port " + getPort());
  }
  
  /**
   * This method overrides the one in the superclass.  Called
   * when the server stops listening for connections.
   */
  protected void serverStopped()
  {
    System.out.println
      ("Server has stopped listening for connections.");
  }
  
  //Class methods ***************************************************
  
  /**
   * This method is responsible for the creation of 
   * the server instance (there is no UI in this phase).
   *
   * @param args[0] The port number to listen on.  Defaults to 5555 
   *          if no argument is entered.
   */
  public static void main(String[] args) 
  {
    int port = 0; //Port to listen on

    try
    {
      port = Integer.parseInt(args[0]); //Get port from command line
    }
    catch(Throwable t)
    {
      port = DEFAULT_PORT; //Set port to 5555
    }
	
    EchoServer sv = new EchoServer(port);
    
    try 
    {
      sv.listen(); //Start listening for connections
    } 
    catch (Exception ex) 
    {
      System.out.println("ERROR - Could not listen for clients!");
    }
  }
}
//End of EchoServer class
